import Axios from 'axios'
import { ElNotification } from 'element-plus'
import { toSSO } from '@/common/util'
import { userStoreWithOut } from '@/stores/modules/userStore'
import configs from '@/config.ts'
import WaterMark from '@/common/watermark'

let store = null
/**
 * axios实例
 * @type {AxiosInstance}
 */
let instance = Axios.create({
    headers: {
        'x_requested_with': 'XMLHttpRequest'
    },
    timeout: 600000, // 10分钟超时时间
})

/**
 * axios请求过滤器
 */
instance.interceptors.request.use(
    (config) => {
        if (store === null) {
            store = userStoreWithOut()
        }
        if (store.getJwtToken) { // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = store.getJwtToken
        }
        config.url = configs.service.baseInterfaceUrl + config.url
        return config
    },
    (err) => {
        return Promise.reject(err)
    })

export const doLogout = function (message) {
    // WaterMark.out()
    if (store === null) {
        store = userStoreWithOut()
    }
    store.setUserInfo(null)
    store.setUserName(null)
    store.setAccessToken(null)
    store.setMenus(null)
    store.setNoJwtToken(null)
    toSSO().then(() => {
        ElNotification.error({
            title: '提示',
            message: message
        })
    }).catch((err) => {
        console.error(err)
    })
}

/**
 * axios响应过滤器
 */
instance.interceptors.response.use(
    (response) => {
        //token失效单独处理 跳转到登录页面
        if(response.data.code=='401'){
            doLogout(response.data.message)
        }
        return response
    },
    (error) => {
        debugger;
        console.error(error)
        if (error.response.status === 500) {
            let { data } = error.response
            if (data !== null && data !== undefined) {
                let { code, message } = data
                if (code === '401') {
                    doLogout(message)
                }
            } else {
                ElNotification.error({
                    title: '提示',
                    message: error.response.data.message
                })
            }
        } else {
            return Promise.reject(error.response)
        }
    })

export default instance
